<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="deps"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template v-slot="{ data }">
          <el-row
            type="flex"
            align="middle"
            justify="space-between"
            style="width: 100%; height: 40px"
          >
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="depHandle($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDialog ref="addDep" :show-dialog.sync="showDialog" :origin-deps="originDeps" :current-id="currentId" @updateDeps="getDepartment" />
  </div>
</template>
<script>
import { transListToTree } from '@/utils'
import { getDepartment, delDept } from '@/api/department'
import AddDialog from './components/AddDialog.vue'
export default {
  name: 'Department',
  components: {
    AddDialog
  },
  data() {
    return {
      showDialog: false,
      deps: [],
      originDeps: [],
      currentId: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  async created() {
    this.getDepartment()
  },
  methods: {
    depHandle(command, id) {
      if (command === 'add') {
        this.currentId = id + ''
        this.showDialog = true
      } else if (command === 'edit') {
        this.$refs.addDep.getDepDetail(id)
        this.currentId = id + ''
        this.showDialog = true
      } else {
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDept(id)
          this.$message({
            type: 'success',
            message: '删除部门成功'
          })
          this.getDepartment()
        })
      }
    },
    async getDepartment() {
      const res = await getDepartment()
      this.deps = transListToTree(res, 0)
      this.originDeps = res
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
  .tree-manager {
    width: 50px;
    display: inline-block;
    margin: 10px;
  }
}
</style>
